package com.hrt.datasender.datasent.serial;

import com.hrt.serial.modbus.ModbusDataFrameDecoderBase;
import com.hrt.serial.modbus.MsgLengthException;

public class DataFrameDecoder212 extends ModbusDataFrameDecoderBase {
    
    private final int msgMinLength = 6;
    
    private final int dataLengthBit = 4;
    
    private final int msgPrefixLength = 6;
    
    private final int msgSuffixLength = 6;

    public DataFrameDecoder212(byte[] msg) {
        this.msg = msg;
    }

    @Override
    public byte[] next() {

        String allMsg = new String(msg);

        /**
         * 为了解析得到报文的长度，必须要有6个字节，##+四位长度，如##0076，表示报文长度为76
         */
        if (allMsg.length() < msgMinLength) {
            throw new MsgLengthException("数据长度不足");
        }

        String dataLengthStr = allMsg.substring(2, 2 + dataLengthBit);
        int dataLength = Integer.parseInt(dataLengthStr);

        int expectDataLength = msgPrefixLength + dataLength + msgSuffixLength;// ## + 四位长度 + 报文 +
                                                          // CRC验证码 + 回车换行符
        if ((allMsg.length() - readedPosition) < expectDataLength) {
            throw new MsgLengthException("数据长度不足");
        }

        byte[] targetMsg = new byte[expectDataLength];

        System.arraycopy(msg, readedPosition, targetMsg, 0, expectDataLength);

        readedPosition += expectDataLength;

        return targetMsg;

    }

}
